using UnityEngine;
using System.IO;
using System.Collections.Generic;
using System;

/// <summary>
/// 配置类的基类 (每个配置类必须有唯一id)
/// </summary>
public class ConfigBase { public string id; public ConfigBase() { } }

public class JsonMgr : MonoBehaviour
{
    private Dictionary<Type, List<ConfigBase>> _dic;

    /// <summary>
    /// 初始化
    /// </summary>
    public void Init()
    {
        _dic = new Dictionary<Type, List<ConfigBase>>();
    }

    /// <summary>
    /// 销毁
    /// </summary>
    public void Destroy()
    {
        _dic.Clear();
        _dic = null;
    }

    /// <summary>
    /// 获取配置信息
    /// </summary>
    public List<T> GetConfigs<T>() where T: ConfigBase    
    {
        Type t = typeof(T);
        if (!_dic.ContainsKey(t))
            _ReadJsonFile(t);

        List<T> list = new List<T>();

        foreach (var item in _dic[t])
            list.Add(item as T);

        return list;
    }

    ////////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// 读取Json文件
    /// </summary>
    private void _ReadJsonFile(Type t)
    {
        string data = File.ReadAllText(_GetConfigPath(t));
        var list = JsonTool.ToObjectList<ModelInfo>(data);

        List<ConfigBase> clist = new List<ConfigBase>();
        foreach (var item in list)
            clist.Add(item);

        _dic.Add(t, clist);
    }

    /// <summary>
    /// 获取json配置表的路径
    /// </summary>
    private string _GetConfigPath(Type t)
    {
        string path = string.Format("Configs/{0}.json", t.ToString());
        return string.Format("{0}/{1}", Application.streamingAssetsPath, path);
    }
}

